package com.boot.controller;

import com.boot.result.Result;
import com.boot.result.ResultCodeNum;
import com.boot.service.AliyunOSSService;
import com.boot.service.LocalFileStorageService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("common")
public class CommonController {
    @Autowired
    private LocalFileStorageService localFileStorageService;

    @Autowired
    private AliyunOSSService aliyunOSSService;

    @Operation(summary = "上传文件")
    @PostMapping("upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String newFileName = UUID.randomUUID()+"."+ extension;
            String uploadPath = aliyunOSSService.upload(file, "images", newFileName);
            return Result.success(uploadPath);
        } catch (IOException e) {
            return Result.build(null, ResultCodeNum.UPLOAD_FILE_FAILED);
        }
    }


    @PostMapping("delete")
    public void upload(@RequestParam("fileName") String fileName) {
        aliyunOSSService.delete(fileName);
    }

}
